home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8690 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: news1.h1.usa.pipeline.com!usenet
  2. From: grantp@usa.pipeline.com(Pete)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Yet a question about random
  5. Date: 26 Feb 1996 00:35:58 GMT
  6. Organization: Kalevi, Inc.
  7. Message-ID: <4gqv9e$q80@news1.usa.pipeline.com>
  8. NNTP-Posting-Host: pipe11.h1.usa.pipeline.com
  9. X-PipeUser: grantp
  10. X-PipeHub: usa.pipeline.com
  11. X-PipeGCOS: (Pete)
  12. X-Newsreader: Pipeline USA v3.3.0
  13.  
  14. On Feb 25, 1996 12:47:24 in article <Yet a question about random>,
  15. 'm151843@proffa.cc.tut.fi (Edvard Majakari)' wrote: 
  16.  
  17.  
  18. >I use the following function to produce (pseudo)random numbers 
  19. >between 1...top. However, this algorithm seems to be far from 
  20. >good pseudorandom. But the hint was in rand manpage - any good 
  21. >ideas to produce better 'random' numbers? 
  22. >-----&<------------------------&<------------------------------- 
  23. >#include <stdlib.h> 
  24. >#include <sys/time.h> 
  25. >#include <unistd.h> 
  26. >int randomize(float top) { 
  27. >    int rnum; 
  28. >    timeval seed;  //see struct timeval for further details 
  29. >    gettimeofday(&seed, NULL); 
  30. >    srand(seed.tv_usec); //initialize with millisecs 
  31. >    rnum = 1+(int) (top*rand()/(RAND_MAX+1.0)); 
  32. >    return rnum; 
  33. >} 
  34. Two things: 
  35.  
  36. First, you should call srand() only once in your program.   
  37. Reinitializing the random number generator each time rand() 
  38. is called is not likely to produce a good distribution. 
  39.  
  40. Second, I'm not quite sure what the desired result is.  Is it 
  41. an integer in the set (1, top)?  If so, just use the remainder 
  42. operator: 
  43.      
  44.       return (rand() % (int)top) + 1; 
  45.  
  46.  
  47. -- 
  48. Pete Grant 
  49. Kalevi, Inc. 
  50. Software Engineering & development
  51.